<?php
namespace common\modules\system;

use common\core\modularity\ModuleServiceInterface;
use common\modules\system\models\Menu;
use common\helpers\Constants;
use yii\helpers\Url;
use common\modules\rbac\backend\components\MenuHelper;

class SystemService implements ModuleServiceInterface
{

    public function getServiceId()
    {
        return 'systemService';
    }
    
    private function getRootMenu() {
        $action = getApp()->requestedAction;
        $currentMenu = Menu::findOne([
            'url' => '/' . $action->uniqueId
        ]);
        if ($currentMenu) {
            $rootMenu = Menu::getRootMenu($currentMenu->id);
        }
        else {
            $currentMenu = Menu::find()->Where(['like','url', '/' . getApp()->controller->module->id])->one();
            if ($currentMenu) {
                $rootMenu = Menu::getRootMenu($currentMenu->id);
            }
        }
        return $rootMenu;
    }

    public function getTopAdminMenusHtml()
    {
        $html = '';
        $rootMenu = $this->getRootMenu();
        if ($rootMenu) {
            $html = '<ul class="nav navbar-nav">';
            $menus = Menu::getChildren('backend', null, Constants::STATUS_ENABLE);
            foreach ($menus as $m) {
                $url = $m->url == '#' ? '#' : Url::to($m->url);
                if ($rootMenu->url === $url) {
                    $html .= '<li class="active"><a href="' . $url . '">' . $m->name . '</a></li>';
                } else {
                    $html .= '<li><a href="' . $url . '">' . $m->name . '</a></li>';
                }
            }
            $html .= '</ul>';
        }
        return $html;
    }

    public function getSidebarAdminMenuItems()
    {
        $menus = [];
        $rootMenu = $this->getRootMenu();
        if ($rootMenu) {
            $menus = MenuHelper::getAssignedMenu(getMyId(), 'backend', $rootMenu->id);
        }
        return $menus;
    }
}
